const moment = require('moment');
const Utils = require('../../utils/Utils');
const Code = require("../../../config/code");
/**
 * Http助手
 */
class HttpInfo {
    constructor() {
        this.pid = "";
        this.sTime = 0; //開始時間
        this.uTime = 0;//上次操作時間
        this.eTime = 0;//結束時間
        this.port = 0;
        this.token = "";
        this.platform = "";
    }
}
class HttpManager {
    constructor() {
        this.httpPools = [];
        this.httpKeys = {};
        this.tokenOutTime = 30;//三十分钟的token超时时间
        this.interval = -1;
        this.init();
    }
    init() {
        /**
         * 定时器，把超时的token移除
         */
        this.interval = setInterval(this.clearKeys, 1000 * 60 * this.tokenOutTime);
    }
    clearKeys() {
        for (let key in this.httpKeys) {
            if (moment().isAfter(this.httpKeys[key].eTime)) {
                this.removeByPid(key);
            }
        }
    }
    
    setOne(info) {
        let one;
        if (this.httpKeys[info.pid]) {
            one = this.httpKeys[info.pid];
        } else {
            one = this.getOne();
            one.pid = info.pid;
        }
        one.sTime = moment();
        one.uTime = moment();//上次操作時間
        one.eTime = moment(one.uTime).add(this.tokenOutTime, 'minutes');
        one.port = info.port;
        one.platform = info.platform;
        one.token = Utils.generateNanoIdToken();
        this.httpKeys[info.pid] = one;
        return one;
    }
    getByPid(pid, token) {
        if (this.httpKeys[pid]) {
            if (this.httpKeys[pid].token == token && moment().isAfter(this.httpKeys[pid].eTime)) {
                this.removeByPid(pid);
                return Code.HTTP_TOKEN_OUT_TIME;
            }
            this.httpKeys[pid].uTime = moment();
            this.httpKeys[pid].eTime = moment().add(10, 'minutes');
            return { code: Code.SUCCESS, data: this.httpKeys[pid] };
        } else {
            return Code.HTTP_NOT_EXIT
        }
    }
    getOne() {
        if (this.httpPools.length > 0) {
            return this.httpPools.shift();
        } else {
            return new HttpInfo();
        }
    }
    removeByPid(pid) {
        if (this.httpKeys[pid]) {
            this.httpKeys[pid].token = "";
            this.httpKeys[pid].sTime = 0; //開始時間
            this.httpKeys[pid].eTime = 0;//結束時間
            this.httpKeys[pid].port = 0;
            this.httpPools.push(this.httpKeys[pid]);
            delete this.httpKeys[pid];
        }
    }
}

module.exports = new HttpManager();